package org.hshk.message.controller;

import com.google.gson.Gson;
import io.swagger.annotations.*;
import org.apache.log4j.Logger;
import org.hshk.message.BaseController;
import org.hshk.message.entity.CpMsgMember;
import org.hshk.message.entity.CpMsgMemberSign;
import org.hshk.message.entity.CpMsgPayDetail;
import org.hshk.message.entity.CpMsgPayruleDetail;
import org.hshk.message.repository.CpMsgMemberRepository;
import org.hshk.message.repository.CpMsgMemberSignRepository;
import org.hshk.message.repository.CpMsgPayDetailRepository;
import org.hshk.message.repository.MsgPayruleDetailRepository;
import org.hshk.message.service.StestService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by GaoChuang on 2017/3/27.
 */
@Api(value = "短信商户 API")
@RestController
@RequestMapping("/msgOrgs")
public class MsgOrgAddController extends BaseController {
    private static final Logger log = Logger.getLogger(MsgOrgAddController.class);
    @Autowired
    //商户信息查询 单表对象
    CpMsgMemberRepository cpMsgMemberRepository;
    //@Autowired
    //CpMsgMemberMapper cpMsgMemberMapper;
    @Autowired
    MsgPayruleDetailRepository msgPayruleDetailRepository;
    @Autowired
    CpMsgPayDetailRepository cpMsgPayDetailRepository;
    @Autowired
    CpMsgMemberSignRepository cpMsgMemberSignRepository;
    @Autowired
    StestService stestService;
    //@Autowired
    //CpMsgPayDetailMapper cpMsgPayDetailMapper;
    private BeanUtils beanUtils;
    //线程对象保存
    private static final ThreadLocal<Gson> local = new ThreadLocal<Gson>();

    //获取当前线程操作对象的使用权
    private Gson getGson() {
        if (null == local.get()) {
            Gson gson = new Gson();
            local.set(gson);
        }
        return local.get();
    }

    @ApiOperation(value = "短信商户,线下短信充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "商户id", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "brandId", value = "品牌id", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "detailId", value = "短信充值小id", required = true, dataType = "int", paramType = "path"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")
    })
    @ResponseBody
    @RequestMapping(value = "/orgId/{orgId}/brandId/{brandId}/detailId/{detailId}", method = RequestMethod.PUT, produces = "application/json")
    public String msgMembersLineRecharge(@PathVariable int orgId,
                                         @PathVariable int brandId,
                                         @PathVariable int detailId) {
        Map<String, Object> paramMsg = new HashMap<String, Object>();
        int nowDate = (int) (System.currentTimeMillis() / 1000);
        try {
            log.info("MsgMemberAddController.msgMembersLineRecharge " + "orgId" + orgId + "brandId" + brandId +
                    "detailId" + detailId);
            if (0 == orgId) {
                paramMsg.put("orgId", "参数不对");
            }
            if (0 == brandId) {
                paramMsg.put("brandId", "参数不对");
            }
            if (0 == detailId) {
                paramMsg.put("detailId", "参数不对");
            }
            if (0 != paramMsg.size()) {
                return getGson().toJson(paramMsg);
            }
            //根据detailId 获取充值条数
            CpMsgPayruleDetail cpMsgPayruleDetail = msgPayruleDetailRepository.findById(detailId);
            if (null == cpMsgPayruleDetail) {
                log.error("MsgMemberAddController.msgMembersLineRecharge " + "msgPayruleDetail表参数不存在");
                paramMsg.put("resultCode", "fail");
                paramMsg.put("resultMsg", "msgPayruleDetail表参数不存在");
                return getGson().toJson(paramMsg);
            }
            //获取剩余条数
            CpMsgMember cpMsgMember = cpMsgMemberRepository.findByOrgIdAndBrandId(orgId, brandId);
            if (null == cpMsgMember) {
                log.error("MsgMemberAddController.msgMembersLineRecharge " + "cpMsgMember表参数不存在");
                paramMsg.put("resultCode", "fail");
                paramMsg.put("resultMsg", "cpMsgMember表参数不存在");
                return getGson().toJson(paramMsg);
            }
            //判断短信厂商是光通互动还是互亿无线
            CpMsgMemberSign cpMsgMemberSign = cpMsgMemberSignRepository.findByBrandIdAndOrgIdAndIsUsed(brandId, orgId, "Yes");
            if (null == cpMsgMemberSign) {
                log.error("MsgMemberAddController.msgMembersDirectRecharge " + "cpMsgMember Sign表参数不存在");
                paramMsg.put("resultCode", "fail");
                paramMsg.put("resultMsg", "cpMsgMemberSign表参数不存在");
                return getGson().toJson(paramMsg);
            }
            //判断厂商
            CpMsgPayDetail cpMsgPayDetail = new CpMsgPayDetail();
            if(1 == cpMsgMemberSign.getFactoryId()){
                cpMsgPayDetail.setFactoryId(1);
            }
            if(2 == cpMsgMemberSign.getFactoryId()){
                cpMsgPayDetail.setFactoryId(2);
            }
            //保存累加的条数和剩余条数
            CpMsgMember cpMsgMember1 = new CpMsgMember();
            beanUtils.copyProperties(cpMsgMember, cpMsgMember1);
            cpMsgMember1.setUpdateDate(nowDate);
            cpMsgMember1.setTotalCount(cpMsgMember.getTotalCount() + cpMsgPayruleDetail.getCount());
            cpMsgMember1 = cpMsgMemberRepository.save(cpMsgMember1);
            //保存到充值记录表中

            cpMsgPayDetail.setBrandId(brandId);
            cpMsgPayDetail.setUid(orgId);
            cpMsgPayDetail.setPayruleId(detailId);
            cpMsgPayDetail.setPayCount(cpMsgPayruleDetail.getCount());
            cpMsgPayDetail.setPayAmount(cpMsgPayruleDetail.getAmount());
            cpMsgPayDetail.setPayType("offline");
            cpMsgPayDetail.setStatus("finished");
            cpMsgPayDetail.setUpdateDate(nowDate);
            cpMsgPayDetail.setCreateDate(nowDate);
            cpMsgPayDetail.setOrderNo("0");
            cpMsgPayDetailRepository.save(cpMsgPayDetail);
            return getGson().toJson(cpMsgMember1);
        } catch (Exception ex) {
            //出现异常时
            log.error("MsgMemberAddController.msgMembersLineRecharge" + ex.getMessage());
            ex.printStackTrace();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("resultCode", "fail");
            resultMap.put("resultMsg", "失败");
            return getGson().toJson(resultMap);
        }
    }



    @ApiOperation(value = "短信商家,申请充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "payDetailId", value = "支付明细id", required = true, dataType = "int", paramType = "path")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")
    })
    @ResponseBody
    @RequestMapping(value = "/{payDetailId}", method = RequestMethod.PUT, produces = "application/json")
    public String msgMembersApplyRecharge(@PathVariable int payDetailId) {
        Map<String, Object> paramMsg = new HashMap<String, Object>();
        int nowDate = (int) (System.currentTimeMillis() / 1000);
        try {
            log.info("MsgMemberAddController.msgMembersApplyRecharge" + "支付明细id" + payDetailId);
            CpMsgPayDetail cpMsgPayDetail = cpMsgPayDetailRepository.findOne(payDetailId);
            if (null == cpMsgPayDetail) {
                log.error("MsgMemberAddController.msgMembersApplyRecharge " + "cpMsgPayDetail表参数不存在");
                paramMsg.put("resultMsg", "cpMsgPayDetail表参数不存在");
                return getGson().toJson(paramMsg);
            }
            if ("payed".equals(cpMsgPayDetail.getStatus())) {
                //获取剩余条数
                //CpMsgMember cpMsgMember = cpMsgMemberMapper.findByUidANDBrandId(cpMsgPayDetail.getUid(), cpMsgPayDetail.getBrandId());
                /**
                 * Creat by yyl
                 * mppper转jpa
                 * 下面一些要用到 CpMsgMember 的参数,用 list.get(0) 代替
                 */
                List<CpMsgMember> list = cpMsgMemberRepository.findByBrandIdAndOrgId(cpMsgPayDetail.getBrandId(),cpMsgPayDetail.getUid());

                if (null == list.get(0)) {
                    log.error("MsgMemberAddController.msgMembersApplyRecharge " + "cpMsgMember表参数不存在");
                    paramMsg.put("resultMsg", "cpMsgMember表参数不存在");
                    return getGson().toJson(paramMsg);
                }
                //保存累加的条数和剩余条数
                //cpMsgMemberMapper.upDateByBalanceCountAndTotalCountAndUpdateDate(list.get(0).getId(), list.get(0).getBalanceCount(),
                //        list.get(0).getTotalCount() + cpMsgPayDetail.getPayCount(), list.get(0).getUpdateDate());
                /**
                 * Creat by yyl
                 * 2017年6月22日15:20:03
                 */
                cpMsgMemberRepository.upDateByBalanceCountAndTotalCountAndUpdateDate(list.get(0).getId(), list.get(0).getBalanceCount(),
                        list.get(0).getTotalCount() + cpMsgPayDetail.getPayCount(), list.get(0).getUpdateDate());


                //更改充值记录表里的申请变成成功状态
                //cpMsgPayDetailMapper.upDateByStatus(payDetailId, "finished");
                /**
                 * Creat by yyl
                 * 2017年6月22日16:23:36
                 * mapper转jpa
                 */
                cpMsgPayDetailRepository.updateById( payDetailId ,"finished");

                paramMsg.put("resultCode", "success");
                return getGson().toJson(paramMsg);
            } else {
                paramMsg.put("resultCode", "fail");
                paramMsg.put("resultMsg", "状态为：" + cpMsgPayDetail.getStatus() + "不是可充值状态");
                return getGson().toJson(paramMsg);
            }

        } catch (Exception ex) {
            //出现异常时
            log.error("MsgMemberAddController.msgMembersApplyRecharge" + ex.getMessage());
            ex.printStackTrace();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("resultCode", "fail");
            resultMap.put("resultMsg", "失败");
            return getGson().toJson(resultMap);
        }
    }
}
